package cn.yangliu.nacos.management.service.oauth2.impl;

import java.util.Objects;

import cn.yangliu.jpa.base.service.impl.JpaServiceImpl;
import cn.yangliu.nacos.comm.model.Oauth2InsertModel;
import cn.yangliu.nacos.comm.model.Oauth2UpdateOtherModel;
import cn.yangliu.nacos.comm.model.Oauth2UpdateOtherPasswordModel;
import cn.yangliu.nacos.comm.model.Oauth2UserModel;
import cn.yangliu.nacos.comm.oauth.Oauth2Service;
import cn.yangliu.nacos.management.entity.oauth2.Oauth2User;
import cn.yangliu.nacos.management.entity.sys.User;
import cn.yangliu.nacos.management.repository.oauth2.Oauth2UserRepository;
import cn.yangliu.nacos.management.repository.sys.UserRepository;
import cn.yangliu.nacos.management.service.oauth2.Oauth2UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * The type of nacos.
 *
 * @author 问道于盲
 * @date 2020 -01-01
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class Oauth2UserServiceImpl extends JpaServiceImpl<Oauth2User, Long, Oauth2UserRepository>
        implements Oauth2UserService {

    /**
     * current class instance's member.
     * The Oauth 2 service.
     */
    @Autowired
    private Oauth2Service oauth2Service;

    /**
     * current class instance's member.
     * The User repository.
     */
    @Autowired
    private UserRepository userRepository;

    /**
     * Insert oauth 2 user model.
     *
     * @param model the model
     * @param token the token
     * @return the oauth 2 user model
     */
    @Override
    public Oauth2UserModel insert(Oauth2InsertModel model, String token) {
        return oauth2Service.insert(model, token);
    }

    /**
     * Update oauth 2 user model.
     *
     * @param model the model
     * @param token the token
     * @return the oauth 2 user model
     */
    @Override
    public Oauth2UserModel update(Oauth2UpdateOtherModel model, String token) {
        return oauth2Service.updateOther(model, token);
    }

    /**
     * Update password boolean.
     *
     * @param model the model
     * @param token the token
     * @return the boolean
     */
    @Override
    public boolean updatePassword(Oauth2UpdateOtherPasswordModel model, String token) {
        return oauth2Service.updateOtherPassword(model, token);
    }

    /**
     * Delete by id.
     *
     * @param id the id
     */
    @Override
    public void deleteById(Long id) {
        super.deleteById(id);
        User user = userRepository.findByOauth2Id(id);
        if (Objects.nonNull(user)) {
            userRepository.delete(user);
        }
    }
}
